package net.ojbk.study.twobox.service;

import net.ojbk.study.twobox.beans.po.Class;
import net.ojbk.study.twobox.beans.po.Job;
import net.ojbk.study.twobox.dao.JobMapper;
import net.ojbk.study.twobox.dao.LessontypeMapper;
import net.ojbk.study.twobox.dao.StaffMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/4/17
 * Time: 23:30
 * Description: No Description
 */
@Service
public class ClassService extends SupperService<Class> {

    @Autowired
    LessontypeMapper lessontypeMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    JobMapper jobMapper;

    public boolean time_IsOK(Date time1, Date time2) {

        LocalDateTime now_time1 = LocalDateTime.ofInstant(time1.toInstant(), ZoneId.systemDefault());
        LocalDateTime now_time2 = LocalDateTime.ofInstant(time2.toInstant(), ZoneId.systemDefault());
        if (now_time2.toLocalDate().toEpochDay() - now_time1.toLocalDate().toEpochDay() > 0)
            return true;
        return false;

    }

    public void check(Class o) throws Exception {
        if (!time_IsOK(o.getBegintime(), o.getEndtime()))
            throw new Exception("结束时间要晚于开始时间。");
        // 判断课程外键是否纯在
        if (lessontypeMapper.selectByPrimaryKey(o.getLessontypeid()) == null)
            throw new Exception("课程不存在！");
        // 教师id和班主任id也需要检查该外键是否存在
        if (staffMapper.selectByPrimaryKey(o.getTeacherid()) == null || staffMapper.selectByPrimaryKey(o.getUserid()) == null)
            throw new Exception("教师id和班主任id也需要检查该外键是否存在！");
    }

    @Override
    public void addOne(Class o, BindingResult br) throws Exception {
        this.validated(br, Class.class);
        check(o);
        this.dao.insert(o);
    }

    @Override
    public void deleteOne(int id) throws Exception {
        // 先检查crm_job表当中有没有班级id,如果有则不允许删除
        Job job = new Job();
        job.setClassid(id);
        if (jobMapper.selectCount(job) > 0 )
            throw new Exception("先检查crm_job表当中有没有班级id,如果有则不允许删除");
        this.dao.deleteByPrimaryKey(id);
    }

    @Override
    public void updateOne(Class o, BindingResult br) throws Exception {
        this.validated(br, Class.class);
        check(o);
        this.dao.updateByPrimaryKeySelective(o);
    }
}
